package com.ingrun.tuboshu.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatis-plus自动填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //自动填充创建时间
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtil.date());
        //自动填充创建人姓名
        this.strictInsertFill(metaObject, "createBy", String.class, getCurrentUsername());
        this.setFieldValByName("updateTime", DateUtil.date(), metaObject);
        this.setFieldValByName("updateBy", getCurrentUsername(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", getCurrentUsername(), metaObject);
    }

    private String getCurrentUsername() {
        String name = "未登录用户";
//        try {
//            name = String.valueOf(SecurityUtils.getUserId());
//        } catch (Exception e) {
//            log.warn("插入mybatisPlus获取当前登陆用户异常");
//        }
//        return name;

        return name;
    }
}
